<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/10/23
 * Time: 11:40
 */
namespace app\share\controller;

use app\share\model\PingStore;
use app\share\model\SendSms;
use app\share\model\UploadImg;
use think\Controller;
use think\Validate;
use think\Db;

class IpStore extends Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->ping_store = new PingStore();
        $this->upload_img = new UploadImg();
        $this->send_code  = new SendSms();
    }
    //找回密码
    public function retrievePwdAdd()
    {
        $input = input();
        $validate = new Validate([
            ['mobile', 'require|max:11|/^1[3-8]{1}[0-9]{9}$/', '手机号码不能为空|手机号码不能超过11个字符|手机号码格式不正确'],
            ['code', 'require', '验证码不能为空'],
            ['admin_pwd', 'require', '密码不能为空'],
            ['rep_pwd', 'require', '确认密码不能为空'],
        ]);
        if(!$validate->check($input))
        {
            return ['code'=>-1002,'msg'=>$validate->getError()];
        }
        //查询改手机号码是否注册
        $res = Db::name("admin_user")->field("key")->where(['admin_tel'=>$input['mobile']])->find();
        if(empty($res))
        {
            return ['code'=>-2001,'msg'=>"该手机号码不是管理员账号"];
        }
        if($input['admin_pwd'] != $input['rep_pwd'])
        {
            return ['code'=>-2002,'msg'=>"密码和确认密码不一致"];
        }
        //验证验证码
        $mysql_code = $this->send_code->retrievePwd($input['mobile']);
        if(empty($mysql_code))
        {
            return ['code'=>-2003,'msg'=>"验证码已过期,请重新获取"];
        }
        if($mysql_code['code_num'] != $input['code'])
        {
            return ['code'=>-2004,'msg'=>"输入验证码错误"];
        }
        //修改入库
        $new_pwd = md5($input['admin_pwd'] . $res['key']);
        $res1 = Db::name("admin_user")->where(['admin_tel'=>trim($input['mobile']), 'admin_pwd'=>$new_pwd])->find();
        if($res1)
        {
            return ['code'=>-2006,'msg'=>"和旧密码一致,请直接去登陆"];
        }
        //开启事务
        Db::startTrans();
        try{
            Db::name("admin_user")->where(['admin_tel'=>trim($input['mobile'])])->update(['admin_pwd'=>$new_pwd]);
            Db::name("yan_code")->where(['code_id'=>$mysql_code['code_id']])->update(['code_status'=>2]);
            Db::commit();
            return ['code'=>200,'msg'=>"密码找回成功"];
        } catch (\Exception $e){
            Db::rollback();
            return ['code'=>-2005,'msg'=>"密码找回失败"];
        }
    }
    //找回密码发短信
    public function retrievePwd()
    {
        $input = input();
        $validate = new Validate([
            ['mobile', 'require|max:11|/^1[3-8]{1}[0-9]{9}$/', '手机号码不能为空|手机号码不能超过11个字符|手机号码格式不正确'],
        ]);
        $code = mt_rand(10000,99999);
        if(!$validate->check($input))
        {
            return ['code'=>-1002,'msg'=>$validate->getError()];
        }
        //查询改手机号码是否注册
        $res = Db::name("admin_user")->field("key")->where(['admin_tel'=>$input['mobile']])->find();
        if(empty($res))
        {
            return ['code'=>-2001,'msg'=>"该手机号码不是管理员账号"];
        }
        return $this->send_code->sendSms($input['mobile'], $code);
    }
    //退出接口
    public function loginExit()
    {
        $userid = get_user_id(input()['token']);
        $file_token = str_replace("\\", '/', ROOT_PATH ."public".DS."apitoken".DS.$userid.DS.input()['token']);
        unlink($file_token);
        returnJson(200,  "退出成功")->send();die;
    }
    //15.excel数据进度条状态返回
    public function progress()
    {
        $user_id = get_user_id(input()['token']);
        return $this->ping_store->progressStatus($user_id);
    }

    //12.网络服务地址ip列表数据编辑
    public function edit()
    {
        $input = input();
        $validate = new Validate([
            ['ip_id', 'require', 'id不能为空'],
            ['net_name', 'require', '网络名称不能为空'],
            ['ip_address', 'require', 'ip地址不能为空'],
            ['ip_server', 'require|number', '网络服务器商不能为空|网络服务器商输入格式错误'],
            //['ip_remark', 'require', '修改数据备注不能为空'],
        ]);
        if(!$validate->check($input))
        {
            return ['code'=>-1002,'msg'=>$validate->getError()];
        }

         //当网络服务商 = 其他101，则必须输入新的网络服务商
        if(trim($input['ip_server'])=="101")
        {
            if(isset($input['server_name']))
            {
               if(empty($input['server_name']))
               {
                   returnJson(-2002,  "新的网络服务商不能为空")->send();die;
               }else
               {
                   //新的网络服务商唯一性验证
                   $only = Db::name("server_name")->where(['server_name'=>trim($input['server_name'])])->find();
                   if($only)
                   {
                       returnJson(-2003,  "该网络服务商已经存在")->send();die;
                   }
                   $insert['server_name'] = trim($input['server_name']);
                   $insert['server_time'] = time();
                   Db::name("server_name")->insert($insert);
                   $input['ip_server'] = Db::name('server_name')->getLastInsID();
               }
            }else
            {
                returnJson(-2001,  "请输入新的网络服务商")->send();die;
            }
        }



        //ip地址格式判断
        if( filter_var( $input['ip_address'], FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) ){        //IPv6
        }elseif( filter_var( $input['ip_address'], FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) ){    //IPv4
        }else{
            returnJson(-1002,  "ip地址格式错误")->send();die;
        }
        //网络服务商id判断
        $serverId['server_id'] = $input['ip_server'];
        $res3 = Db::name("server_name")->where($serverId)->find();
        if(empty($res3))
        {
            returnJson(-1002,  "网络服务商id不存在")->send();die;
        }
        //ip查重判断
        $where['ip_address'] = $input['ip_address'];
        $res2 = Db::name("ip_store")
            ->where($where)
            ->where('ip_id','neq',$input['ip_id'])
            ->order(['ip_id'=>'desc'])
            ->find();
        if($res2)
        {
            returnJson(-1002,  "ip地址已存在")->send();die;
        }
        $ping['company_id']   = trim($input['company_id']);
        $ping['depart_id']   = trim($input['depart_id']);
        $ping['net_name']   = trim($input['net_name']);
        $ping['ip_address'] = trim($input['ip_address']);
        $ping['ip_server']  = trim($input['ip_server']);
        $ping['ip_remark']  = trim($input['ip_remark']);
        $ping['ip_update']  = time();
        $ping['ip_user']    = get_user_id($input['token']);
        return $this->ping_store->edit($ping,$input['ip_id']);
    }

    //11.网络服务地址ip列表数据删除
    public function delete()
    {
        $input = input();
        $validate = new Validate([
            ['ip_id', 'require', 'id不能为空'],
        ]);
        if(!$validate->check($input))
        {
            return ['code'=>-1002,'msg'=>$validate->getError()];
        }
        return $this->ping_store->deleteIp($input['ip_id']);
    }
    //10.网络服务地址ip列表显示状态修改
    public function isStatus()
    {
        $input = input();
        $validate = new Validate([
            ['ip_status', 'require|between:1,2', '启用状态不能为空|状态值错误'],
            ['ip_id', 'require', 'id不能为空'],
        ]);
        if(!$validate->check($input))
        {
            return ['code'=>-1002,'msg'=>$validate->getError()];
        }
        return $this->ping_store->isStatus($input['ip_id'],$input['ip_status']);
    }
    //09导入未成功数据
    public function batchError()
    {
        $input = input();
        $batch_id = get_user_id($input['token']);
        $page = empty($input['page']) ? 1 : $input['page'];
        $size = empty($input['size']) ? 10: $input['size'];
        return $this->ping_store->batchNorMal($page,$size,$batch_id);
    }
    //13.批量导入模板上传
    public function upExcel()
    {
        $file = isset($_FILES['file']) ? $_FILES['file'] : "";
        if( empty($file) )
        {
            return ['code'=>-2003, 'msg'=>"文件资源不能为空"];
        }
        return $this->upload_img->uploadExcel($file);

    }
    //07.批量导入数据
    public function batchImport()
    {
        //批量删除前，先请客日志表
        $input = input();
        $batch_id = get_user_id($input['token']);
        Db::name("batch_ip_log")->where(['ip_user'=>$batch_id])->delete();

        $validate = new Validate([
            ['url', 'require', '文件地址不能为空'],
        ]);
        if( !file_exists( $input['url'] ) )
        {
            return ['code'=>-1002,'msg'=>"该路径文件不存在"];
        }
        if(!$validate->check($input))
        {
            return ['code'=>-1002,'msg'=>$validate->getError()];
        }
        $ip_user   = get_user_id(input()['token']);
        return $this->upload_img->uploadPicture($input['url'],$ip_user);

    }
    //05.网络服务地址现实搜索分页
    public function ipIndex()
    {
        $input = input();
        $page = empty($input['page']) ? 1 : $input['page'];
        $size = empty($input['size']) ? 10: $input['size'];
        $where = [];
        if(isset($input['ip_server']))
        {
            if($input['ip_server'] != null)
            {
                $where['ip_server'] = $input['ip_server'];
            }
        }
        if(isset($input['company_id']))
        {
            if($input['company_id'] != null)
            {
                $where['wisdom_ip_store.company_id'] = $input['company_id'];
            }
        }
        if(isset($input['depart_id']))
        {
            if($input['depart_id'] != null)
            {
                $where['wisdom_ip_store.depart_id'] = $input['depart_id'];
            }
        }
        if(isset($input['net_name']))
        {
            if($input['net_name'] != null)
            {
                //ip格式判断
                if( filter_var( $input['net_name'], FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) ){        //IPv6
                    $where['ip_address'] = trim($input['net_name']);
                }elseif( filter_var( $input['net_name'], FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) ){    //IPv4
                    $where['ip_address'] = trim($input['net_name']);
                }else{
                    $where['net_name'] = ['like',"%".trim($input['net_name'])."%"];
                }
            }
        }
        return $this->ping_store->ipSelect($where,$page,$size);
    }
    //06.网络服务商查询
    public function selectServer()
    {
        $data = Db::name("server_name")
            ->field("server_id,server_name")
            ->where(['server_status'=>1])
            ->order(['server_sort','server_id'=>'asc'])
            ->select();
        returnJson(200,  "success", $data)->send();die;
    }
    //04.网络服务地址库添加网络
    public function addIp()
    {
        $input = input();
        $validate = new Validate([
            ['net_name', 'require', '网络名称不能为空'],
            ['ip_address', 'require', 'ip地址不能为空'],
            ['ip_server', 'require|number', '网络服务器商不能为空|网络服务器商输入格式错误'],
            ['company_id', 'require|number', '单位不能为空|单位输入格式错误'],
            ['depart_id', 'require|number', '部门不能为空|部门输入格式错误'],
        ]);
        if(!$validate->check($input))
        {
            return ['code'=>-1002,'msg'=>$validate->getError()];
        }
        //当网络服务商 = 其他101，则必须输入新的网络服务商
        if(trim($input['ip_server'])=="101")
        {
            if(isset($input['server_name']))
            {
               if(empty($input['server_name']))
               {
                   returnJson(-2002,  "新的网络服务商不能为空")->send();die;
               }else
               {
                   //新的网络服务商唯一性验证
                   $only = Db::name("server_name")->where(['server_name'=>trim($input['server_name'])])->find();
                   if($only)
                   {
                       returnJson(-2003,  "该网络服务商已经存在")->send();die;
                   }
                   $insert['server_name'] = trim($input['server_name']);
                   $insert['server_time'] = time();
                   Db::name("server_name")->insert($insert);
                   $input['ip_server'] = Db::name('server_name')->getLastInsID();
               }
            }else
            {
                returnJson(-2001,  "请输入新的网络服务商")->send();die;
            }
        }
        $input['ip_user']   = get_user_id($input['token']);
        $input['ip_update'] = time();
        unset( $input['token'] );
        unset( $input['server_name'] );
        return $this->ping_store->addIpAddress($input);

    }

}